<?php

class SocialMediaInfo_Exception extends Exception
{
}

class SocialMediaInfo
{
  protected $_companyName;
  
  public function __construct( $companyName )
  {
    $companyName = $this->_stripTags($companyName);
    if( empty($companyName) ) {
      throw new SocialMediaInfo_Exception('Given name is empty');
    }
    $this->_companyName = $companyName;        
  }    
  
  protected function _makeGoogleBlogSearchRequest( $query )
  {
    $urlData = array(
      'host' => 'http://blogsearch.google.com',
      'target' => 'blogsearch',
      'query_string' => 'hl=en&ie=UTF-8&q='.urlencode($query).'&btnG=Szukaj+w+blogach&lr=',
      );
    $request = new CustomHttpRequest($urlData);
    $content = $request->getContent();
    return $content;    
  }    
  
  public function getBlogsMentionsAmount()
  {   
    $query = '"'.$this->_companyName.'"';
    $content = $this->_makeGoogleBlogSearchRequest($query);
    $content = $this->_stripTags($content);
    preg_match('/.+of about ([0-9,]+) for.+/',$content,$match);
    if( isset($match[1]) ) {
      $amount = preg_replace('/[^0-9]/','',$match[1]);
      return (int)$amount;
    } else {
      if( preg_match('/did not match/',$content) ) {
        return 0;
      }      
      throw new SocialMediaInfo_Exception('Regexp pattern havent found any pages amount');
    }
  }

    private function _stripTags( $str ) {
        $strs=explode('<',$str);
        $res=$strs[0];
        for($i=1;$i<count($strs);$i++) {
            if(!strpos($strs[$i],'>'))
                $res = $res.'&lt;'.$strs[$i];
            else
                $res = $res.'<'.$strs[$i];
        }
        return strip_tags($res);
    }

}